<?php

namespace App\Models;

use App\Enums\AppMiniPlateEnum;
use App\Exceptions\ApiException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AppMiniPlate extends Model
{
    use HasFactory;

    protected $table = 'sp_app_mini_plate'; //表名
    protected $primaryKey = 'id'; //主键
    protected $guarded = [];

    /**
     * 获取格式化后的配置
     * @return mixed
     */
    public function getContentAttribute($value)
    {
        return json_decode($value,true);
    }


    /**
     * 根据配置的分组获取配置
     */
    public function getMIniPlate($mini_id,$key,$cate_id='')
    {
        $res=self::query()->where('mini_id', $mini_id)->where('key',$key)->select('key','content','description','group','is_open')->first();
        $res=obToArray($res);
        if($key=='great'&&$cate_id>=0){
            $content=[];
            foreach ($res['content'] as $k=>&$v){
                if($v['cate_id']==$cate_id){
                    $content[]=$v;
                }
            }
            $res['content']=$content;

        }
        return $res;
    }


    /**
     * 根据配置的分组获取配置
     */
    public function getMIniOpenPlate($mini_id,$group='')
    {
        $res=self::query()->where('mini_id', $mini_id)->where('group', $group)->where('is_open',1)->select('key','content','description','group','is_open')->get();
        return obToArray($res);
    }

    /**
     * 通过[key=>value]格式更新配置
     * @param array $setting_data
     * @param string $group
     * @return bool
     * @throws ApiException
     */
    public function savePlate($key, $value,$is_open, $mini_ids){
        switch ($key) {
            case 'hot_search':
                 $this->generalCommon($value);
                 break;
            case 'top_recommend':
                 $this->topRecommend($value);
                  break;
            case 'position':
                $this->position($value);
                break;
            case 'waist_recommend':
                $this->topRecommend($value);
                break;
            case 'great_category':
                $value= $this->greatCategory($value,'great_category');
                break;
            case 'great':
                $this->greatCategoryGoods($value);
                break;
            case 'active_banner':
                $this->topRecommend($value);
                break;
            case 'fans':
                $this->fans($value);
                break;
            case 'active_recommend':
                $this->fans($value);
                break;
            case 'goods_recommend':
                $this->greatGoods($value);
                break;
            case 'category_config':
                $is_open=1;
                $value= $this->categoryConfig($value,'category_config');
               break;
           case 'category_recommend':
               $this->fans($value);
               break;
            case 'category_recommend_brand':
                $this->categoryRecommendBrand($value);
                break;
           case 'category_goods':
               $this->categoryGoods($value);
               break;
           case 'care_words':
               $this->careWords($value);
               break;
           case 'super_cost':
               $this->greatGoods($value);
               break;
           case 'care_recommend':
              $this->topRecommend($value);
              break;
          case 'care_goods':
              $this->greatGoods($value);
              break;
          case 'for_you_recommend':
              $this->greatGoods($value);
              break;
          case 'guess_words':
              $this->guessWords($value);
              break;
         case 'week_hot_words':
            $this->week_hot_words($value);
            break;

            default:
                break;
//            throw new BaseException('请选择板块');
        }

        Db::beginTransaction();
        $AppminiPlate=new AppMiniPlate();
        foreach ($mini_ids as $k=> $v) {
            $plate = $AppminiPlate::query()->where('key', $key)->where('mini_id', $v)->first();
            if (!$plate) {

                $plate = self::query()->create([
                    'key' => $key,
                    'group' => AppMiniPlateEnum::getPlateGroup($key),
                    'content' => json_encode($value),
                    'description' =>  AppMiniPlateEnum::getPlateName($key),
                    'mini_id' => $v,
                    'is_open'=>$is_open,
                ]);
            } else {
                $plate->content =$value;
                $plate->is_open = $is_open;
                $plate->save();
            }
            if (!$plate) {
                Db::rollBack();
                return false;
            }
            //更新数据
        }

        $this->flushCache($mini_ids,AppMiniPlateEnum::getPlateGroup($key));

        Db::commit();

        return true;
    }

    //超值分类
  public function  greatCategory($value,$key)
  {
      if(!count(array_filter($value, 'is_array'))){
          throw new ApiException('数组格式有误');
      }
      $values = array_column($value, 'id');
// 找到最大值
      $maxValue = max($values);
      $id= Redis::get('plate'.$key);
      if($maxValue>$id){
          Redis::set('plate'.$key,$maxValue);
      }

      for ($i=0;$i<count($value);$i++){

          $validator = Validator::make($value[$i], [
              'name' => 'required',
          ]);

          if(isset($value[$i]['id'])&&$value[$i]['id']){
              if(!is_numeric($value[$i]['id'])){
                  throw new ApiException('id 格式有误');
              }
              $id=$value[$i]['id'];
          }else{
              Redis::incr('plate'.$key);
              $id= Redis::get('plate'.$key);
          }

          $value[$i]=[
              'id'=>$id,
              'name'=>$value[$i]['name'],
          ];




          if ($validator->fails()) {
              throw new ApiException($validator->getMessageBag()->first());
          }
      }

      return $value;
  }
    //爆品商品
    public function greatCategoryGoods($value)
    {
        if(empty($value)){
            return $value;
        }
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }

        for ($i=0;$i<count($value);$i++){

            $validator = Validator::make($value[$i], [
                'name' => 'required',
            ]);

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

//            if(isset($value[$i]['id'])&&$value[$i]['id']){
//                if(!is_numeric($value[$i]['id'])){
//                    throw new ApiException('id 格式有误');
//                }
//            }else{
//                throw new ApiException('分类id不能为空');
//            }
            if(!is_array($value[$i]['goodsList'])){
                    throw new ApiException('商品格式有误');
            }

            for ($j=0;$j<count($value[$i]['goodsList']);$j++){
                $validator = Validator::make($value[$i]['goodsList'][$j], [
                    'image' => 'required',
                    'title' => 'required',
                    'type' => 'required',
                    'goods_id' => 'required',
                ]);
                if ($validator->fails()) {
                    throw new ApiException($validator->getMessageBag()->first());
                }
            }

        }
        return $value;

    }

    //普通调用
    public function generalCommon($value)
    {
        if(count($value) != count($value, COUNT_RECURSIVE)){
           throw new ApiException('数组格式有误');
        }
    }

    //顶部推荐
    public function topRecommend($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        for ($i=0;$i<count($value);$i++){
            $validator = Validator::make($value[$i], [
                'image' => 'required',
                'return_type' => 'required',
                'link_type' => 'required',
            ]);
            if($value[$i]['link_type']=='2'){
               if(empty($value[$i]['goods_id'])){
                   throw new ApiException('请选择商品');
               }
            if(empty($value[$i]['title'])){
                throw new ApiException('商品名称需出入');
            }
            }else if($value[$i]['link_type']=='1'&&empty($value[$i]['link'])){
                throw new ApiException('请输入链接');
            }

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

        }
    }

    //金刚位置
    public function position($value)
    {
        if(empty($value)){
            return $value;
        }
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        for ($i=0;$i<count($value);$i++){
            $validator = Validator::make($value[$i], [
                'image' => 'required',
                'return_type' => 'required',
                'link_type' => 'required',
                'name' => 'required',
                'remark' => 'required',
            ]);
            if($value[$i]['link_type']=='2'){
                if(empty($value[$i]['goods_id'])){
                    throw new ApiException('请选择商品');
                }
                if(empty($value[$i]['title'])){
                    throw new ApiException('商品名称需出入');
                }
            }else if($value[$i]['link_type']=='1'&&empty($value[$i]['link'])){
                throw new ApiException('请输入链接');
            }

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

        }
    }

    //爆品商品
    public function greatGoods($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        for ($i=0;$i<count($value);$i++){
            $validator = Validator::make($value[$i], [
                'image' => 'required',
                'title' => 'required',
                'type' => 'required',
                'goods_id' => 'required',
            ]);

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

        }
    }

    public function categoryConfig($value,$key)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        $values = array_column($value, 'id');
// 找到最大值
//        $maxValue = max($values);
//        $id= Redis::get('plate'.$key);
//        if($maxValue>$id){
//            Redis::set('plate'.$key,$maxValue);
//        }
        for ($i=0;$i<count($value);$i++){

            if($value[$i]['banner']) {
                if (count($value[$i]['banner']) != count($value[$i]['banner'], COUNT_RECURSIVE)) {
                    throw new ApiException('数组格式有误');
                }
                $validator = Validator::make($value[$i]['banner'], [
                    'image' => 'required',
                    'return_type' => 'required',
                ]);
                if ($value[$i]['banner']['link_type'] == '2') {
                    if (empty($value[$i]['banner']['goods_id'])) {
                        throw new ApiException('请选择商品');
                    }
                    if (empty($value[$i]['banner']['title'])) {
                        throw new ApiException('商品名称需出入');
                    }
                } else if (($value[$i]['banner']['link_type'] == '1' || $value[$i]['banner']['link_type'] == '3') && empty($value[$i]['banner']['link'])) {
                    throw new ApiException('请输入链接');
                }

                if ($validator->fails()) {
                    throw new ApiException($validator->getMessageBag()->first());
                }
            }


            $validator = Validator::make($value[$i], [
                'name' => 'required',
            ]);


            if($value[$i]['goodsList']) {
                if (!is_array($value[$i]['goodsList'])) {
                    throw new ApiException('商品格式有误');
                }


                for ($j = 0; $j < count($value[$i]['goodsList']); $j++) {
                    $validator = Validator::make($value[$i]['goodsList'][$j], [
                        'image' => 'required',
                        'title' => 'required',
                        'type' => 'required',
                        'goods_id' => 'required',
                    ]);
                    if ($validator->fails()) {
                        throw new ApiException($validator->getMessageBag()->first());
                    }
                }
            }


            if($value[$i]['brandList']){
                if(!is_array($value[$i]['brandList'])){
                    throw new ApiException('商品格式有误');
                }

                for ($j=0;$j<count($value[$i]['brandList']);$j++){
                    $validator = Validator::make($value[$i]['brandList'][$j], [
                        'image' => 'required',
                        'return_type' => 'required',
                        'link_type' => 'sometimes',
                    ]);

                    if($value[$i]['brandList'][$j]['return_type']=='3'){
                        if(empty($value[$i]['brandList'][$j]['brand_id'])){
                            throw new ApiException('请选择品牌');
                        }
                    }else{
                        if($value[$i]['brandList'][$j]['link_type']=='2'){
                            if(empty($value[$i]['brandList'][$j]['goods_id'])){
                                throw new ApiException('请选择商品');
                            }
                            if(empty($value[$i]['brandList'][$j]['title'])){
                                throw new ApiException('商品名称');
                            }
                        }else if($value[$i]['brandList'][$j]['link_type']=='1'&&empty($value[$i]['brandList'][$j]['link'])){
                            throw new ApiException('请输入链接');
                        }
                    }

                    if ($validator->fails()){
                        throw new ApiException($validator->getMessageBag()->first());
                    }
                }
            }




            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }
        }

        return $value;
    }


    //粉丝
    public function categoryRecommendBrand($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        for ($i=0;$i<count($value);$i++){
            $validator = Validator::make($value[$i], [
                'image' => 'required',
                'return_type' => 'required',
                'link_type' => 'required',
            ]);

            if($value[$i]['return_type']=='3'){
                if(empty($value[$i]['brand_id'])){
                    throw new ApiException('请选择品牌');
                }
            }else{
                if($value[$i]['link_type']=='2'){
                    if(empty($value[$i]['goods_id'])){
                        throw new ApiException('请选择商品');
                    }
                    if(empty($value[$i]['title'])){
                        throw new ApiException('商品名称需出入');
                    }
                }else if($value[$i]['link_type']=='1'&&empty($value[$i]['link'])){
                    throw new ApiException('请输入链接');
                }
            }


            if ($validator->fails()){
                throw new ApiException($validator->getMessageBag()->first());
            }
        }

    }

    //分类商品
    public function categoryGoods($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }

        for ($i=0;$i<count($value);$i++){

            $validator = Validator::make($value[$i], [
                'name' => 'required',
            ]);

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

            if(isset($value[$i]['id'])&&$value[$i]['id']){
                if(!is_numeric($value[$i]['id'])){
                    throw new ApiException('id 格式有误');
                }
            }else{
                throw new ApiException('分类id不能为空');
            }
            if(!is_array($value[$i]['goodsList'])){
                throw new ApiException('商品格式有误');
            }

            for ($j=0;$j<count($value[$i]['goodsList']);$j++){
                $validator = Validator::make($value[$i]['goodsList'][$j], [
                    'image' => 'required',
                    'title' => 'required',
                    'type' => 'required',
                    'goods_id' => 'required',
                ]);
                if ($validator->fails()) {
                    throw new ApiException($validator->getMessageBag()->first());
                }
            }

        }
        return $value;
    }


    //粉丝
    public function fans($value)
    {
        if(count($value) != count($value, COUNT_RECURSIVE)){
            throw new ApiException('数组格式有误');
        }
            $validator = Validator::make($value, [
                'image' => 'required',
                'return_type' => 'required',
                'link_type' => 'required',
            ]);
            if($value['link_type']=='2'){
                if(empty($value['goods_id'])){
                    throw new ApiException('请选择商品');
                }
                if(empty($value['title'])){
                    throw new ApiException('商品名称需出入');
                }
            }else if(($value['link_type']=='1'||$value['link_type']=='3')&&empty($value['link'])){
                throw new ApiException('请输入链接');
            }

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

    }


    //严选热词
    public function careWords($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        for ($i=0;$i<count($value);$i++){
            $validator = Validator::make($value[$i], [
                'words' => 'required',
                'title' => 'required',
                'goods_id' => 'required',
            ]);

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }

        }
    }

    public function week_hot_words($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }
        for ($i=0;$i<count($value);$i++) {
            $validator = Validator::make($value[$i], [
                'image' => 'required',
                'main_title' => 'required',
                'sub_title' => 'required',
                'return_type' => 'required',
                'link_type' => 'required',
            ]);
            if($value[$i]['link_type']=='2'){
                if(empty($value[$i]['goods_id'])){
                    throw new ApiException('请选择商品');
                }
                if(empty($value[$i]['title'])){
                    throw new ApiException('商品名称需出入');
                }
            }else if(($value[$i]['link_type']=='1'||$value[$i]['link_type']=='3')&&empty($value[$i]['link'])){
                throw new ApiException('请输入链接');
            }

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }
      }

    }

    public function guessWords($value)
    {
        if(!count(array_filter($value, 'is_array'))){
            throw new ApiException('数组格式有误');
        }

        for ($i=0;$i<count($value);$i++) {
            $validator = Validator::make($value[$i], [
                'words' => 'required',
                'return_type' => 'required',
                'link_type' => 'required',
            ]);
            if ($value[$i]['link_type'] == '2') {
                if (empty($value[$i]['goods_id'])) {
                    throw new ApiException('请选择商品');
                }
                if (empty($value[$i]['title'])) {
                    throw new ApiException('商品名称需出入');
                }
            } else if (($value[$i]['link_type'] == '1' || $value[$i]['link_type'] == '3') && empty($value[$i]['link'])) {
                throw new ApiException('请输入链接');
            }

            if ($validator->fails()) {
                throw new ApiException($validator->getMessageBag()->first());
            }
        }

    }

    /**
     * 重设指定分组的缓存
     * @param string $group
     */
    public function flushCache($mini_ids,$group)
    {
        foreach ($mini_ids as $mini_id){
            $list = $this->getMIniOpenPlate($mini_id,$group);
            Redis::hset('plate',$mini_id.$group,json_encode($list));
        }
    }

    /**
     * 组别获取指定小程序配置
     * @param string $group
     */
    public function getAlipayMiniPlate($mini_id, string $group)
    {

         $data=Redis::hget('plate',$mini_id.$group);
         $data=json_decode($data,true)??[];
//        $data = self::getMIniOpenPlate('10001','home_active');
        foreach ($data as $k=>&$v){
            if(is_array($v['content'])){
                if(count(array_filter($v['content'], 'is_array'))){
                    foreach ($v['content'] as $kk=>&$vv){
                        if($vv['goods_id']){
                            $vv['goodsInfo']=Goods::where('id',$vv['goods_id'])->select('min_price','min_lease_term','discount_name','rent_label','min_line_price','business_type','new_grade')->first();
                        }
                        if($vv['banner']&&$vv['banner']['goods_id']){
                            $vv['banner']['goodsInfo']=Goods::where('id',$vv['banner']['goods_id'])->select('min_price','min_lease_term','discount_name','rent_label','min_line_price','business_type','new_grade')->first();
                        }
                        if($vv['goodsList']){
                            foreach ($vv['goodsList'] as $kkk=>&$vvv){
                                $vvv['goodsInfo']=Goods::where('id',$vvv['goods_id'])->select('min_price','min_lease_term','discount_name','rent_label','min_line_price','business_type','new_grade')->first();
                            }
                        }
                        if($vv['brandList']){
                            foreach ($vv['brandList'] as $kkk=>&$vvvv){
                                $vvvv['goodsInfo']=Goods::where('id',$vvvv['goods_id'])->select('min_price','min_lease_term','discount_name','rent_label','min_line_price','business_type','new_grade')->first();
                            }
                        }
                    }
                }else{
                    if($v['goods_id']){
                        $v['goodsInfo']=Goods::where('id',$v['goods_id'])->select('min_price','min_lease_term','discount_name','rent_label','business_type','new_grade')->first();
                    }
                }
            }
        }
        return $data;
    }


}
